<template>
  <div>
      <div class="search content-box">
          <h6 class="title-h6">下载器分析筛选条件</h6>
          <div>
            <el-form  :model="downloaderSearch" class="demo-form-inline" label-position="right" label-width="150px" style="padding-top:20px;text-align:left;padding-left:50px;padding-right:50px;">
                <el-form-item label="时间" class="search-time">
                    <el-button-group  style="margin-bottom:10px;">
                        <el-button :type="dayshow?'success': ''" @click="chooseTimeType('day')">按天</el-button>
                        <el-button :type="!dayshow?'success': ''"  @click="chooseTimeType('time')">按时</el-button>
                    </el-button-group>
                    <div>
                        <el-button-group >
                        <el-button v-for="(item, index) in timeBtnArr" :key="index+item" :type="item == selected?'success': ''"  @click="setTime(index, item)" v-show="!dayshow">{{item}}</el-button>    
                        <el-button v-for="(item, index) in dayBtnArr" :key="index" :type="item == selected?'success': ''"  @click="setTime(index, item)" v-show="dayshow">{{item}}</el-button>
                        <!-- <el-button @click="setTime(0)" class="active"></el-button>
                        <el-button @click="setTime(1)">昨天</el-button>
                        <el-button @click="setTime(7)">最近7天</el-button>
                        <el-button @click="setTime(30)">最近30天</el-button> -->
                        <el-button @click="rangTime()" :type="selected == '自定义'?'success': ''">自定义</el-button>
                    </el-button-group>

                    <el-date-picker v-show="rangTimeShow && dayshow"
                        v-model="downloaderSearch.time"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"  @change="setRang()" :picker-options="pickerOptions">
                    </el-date-picker>
                    <el-date-picker v-show="!dayshow && selected == '自定义'"
                        v-model="downloaderSearch.time"
                        type="date"
                        placeholder="选择日期" @change="checkTime()" :picker-options="pickerOptions">
                    </el-date-picker>
                    </div>
                    
                </el-form-item>
                <el-form-item label="合作站点">
                    <el-select v-model="downloaderSearch.site_id" placeholder="请选择合作站点">
                    <el-option v-for="item in sites" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</el-option>       
                    <!-- <el-option label="上线" value="1"></el-option>
                    <el-option label="下线" value="0"></el-option> -->
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search()">查询</el-button>
                </el-form-item>
            </el-form>
          </div>
      </div>
      <div  style="background:#fff;padding-top:20px; margin-top:10px;border:1px solid #ddd;border-radius: 5px;" ref="element">
        <div class="blok-header clearfix" >
            <el-button-group>
                <el-button v-show="dayshow"><router-link :to="{name: 'xzqindex'}">下载器和物料</router-link></el-button>
                <el-button type="success" >下载器明细</el-button>
                <el-button v-show="dayshow"><router-link :to="{name: 'xzqunitprice'}">成功单价</router-link></el-button>
            </el-button-group>
        </div>
        <el-row style="padding:0px 15px 15px 15px;box-sizing: content-box;">
            <line-chart :chart-data="lineChartData" v-if="lineChartData.seriesData" v-show="tableData.length != 0"></line-chart> 
            <div v-show="tableData.length == 0">暂无相关数据</div> 
        </el-row>
            
            
      </div >
      <div style="background-color:#fff;padding:10px 15px;border:1px solid #ddd;border-radius: 5px;margin-top:10px;">
        <div style="margin-bottom:10px;text-align:right;margin-top:10px"><el-button type="primary"  @click="handleDownload" :loading="downloadLoading">导出列表</el-button></div>
        <div > 
            <el-table
            :data="tableData"
            style="width: 100%;text-align:center" :default-sort = "{prop: 'date', order: 'descending'}">
                <el-table-column
                    prop="week"
                    label="周数" align="center" width="90">
                </el-table-column>
                <el-table-column
                    prop="date" align="center"
                    label="时间">
                </el-table-column>
                <el-table-column
                    prop="open" align="center" :formatter="formatterNumber"
                    label="打开量">
                </el-table-column>
                <el-table-column
                    prop="one" align="center" :formatter="formatterNumber"
                    label="第一步">
                </el-table-column>
                <el-table-column 
                    prop="two" align="center" :formatter="formatterNumber"
                    label="第二步">
                </el-table-column>
                <el-table-column
                    prop="three" align="center" :formatter="formatterNumber"
                    label="第三步">
                </el-table-column>
                <el-table-column
                    prop="success" align="center" :formatter="formatterNumber"
                    label="成功">
                </el-table-column>
                <el-table-column
                    prop="error" align="center" :formatter="formatterNumber"
                    label="失败">
                </el-table-column>
                <el-table-column
                    prop="success_rate" align="center"  
                    label="成功率">
                </el-table-column>
                <el-table-column
                    prop="error_rate" align="center"
                    label="失败率">
                </el-table-column>
            </el-table>
            </div>
        </div>
  </div>
</template>

<script>
import axios from 'axios'
import LineChart from '@/components/XzqData/LineChart'
// import XzqSearch from '@/components/XzqData/XzqSearch'
import {mapGetters, mapActions} from 'vuex'
import {sitesListUrl, getHeader, DownloaderSitedataUrl} from '@/config/config'
import {getDateStr, getDateFromCurrentDate, getNextDay} from '@/utils'
export default {
  name: 'DownloaderDetail',
  data() {
    return {
        // timebtnShow: true 
        dayBtnArr: ['最近7天', '最近30天'],
        timeBtnArr: ['今天', '昨天'],
        rangTimeShow: false,
        selected: null,
        dayshow: true,
        downloadLoading: false,
        sites: [],
        lineChartData: {
            xAxisData: null,
            legendData: null,
            seriesData: null
        },
        pickerOptions: {
            disabledDate(time) {
              return time.getTime() >= Date.now();
            }
        },
        tableData: [] 
    }
  },
  computed: {
    ...mapGetters([
      'downloaderSearch',
      'requestData'
    ])
    
  },
  components: {
      LineChart
  },
  created() {
      axios.get(sitesListUrl, { headers: getHeader()})
      .then(response => {
          if(response.status === 200 && response.data.success) {
              this.sites = response.data.data;
          }else {
              this.$message.error('获取列表失败 !')
          }
        //   console.log(response)
      })
      .catch((e) => {
          this.$message.error('获取列表失败 !')
      })
      if(Array.isArray(this.downloaderSearch.time)) {
          this.selected = '自定义'
          this.rangTimeShow = true;
      }else {
        let start_time = getDateStr(-6);
        let timeObj = {
            time: null,
            start_time: null,
            end_time: new Date(),
        }
        switch(this.downloaderSearch.time) {
          case 7:
            this.selected = '最近7天'
            timeObj['time'] = 7
            timeObj['start_time'] = start_time
            break;
          case 30:
            this.selected = '最近30天'
            timeObj['time'] = 30
            start_time = getDateStr(-29)
            timeObj['start_time'] = start_time
            break;
          default:
            this.selected = '最近7天'
            timeObj['time'] = 7
            timeObj['start_time'] = start_time
        }
        this.setDownloaderSearchTime(timeObj)
      }
      this.downloaderSearch.cycle = 'day'
      setTimeout(() => {
          this.getData()
      })
      // 设置图表组件的数据
    // let _this = this;
    // this.lineChartData['xAxisData'] = [];
    // this.lineChartData['legendData'] = ['打开量', '成功量', '成功率'];
    // this.lineChartData['seriesData']  = [];
    // let openArr = [], successArr = [], sucprobabilityArr = [];
    // this.tableData.forEach(v => {
    //   _this.lineChartData['xAxisData'].push(v.download.time);
    //   openArr.push(v.download.open);
    //   successArr.push(v.download.success);
    //   let num = v.download.sucprobability.replace(/[^0-9]/ig,"");
    //   sucprobabilityArr.push(num);
    // })
    // this.lineChartData['seriesData'][0] = openArr;
    // this.lineChartData['seriesData'][1] = successArr;
    // this.lineChartData['seriesData'][2] = sucprobabilityArr;
    //   console.log( )
    //   console.log(this.downloaderSearch)
  },
  methods: {
    ...mapActions([
      'setDownloaderSearchTime'
    ]),
    setTime(index, str) {
      this.selected = str;
      let timeObj = {
            time: null,
            start_time: null,
            end_time: new Date(),
        }
      switch(str) {
          case '最近7天':
             timeObj.time = 7
             timeObj.start_time = getDateStr(-6)
             this.rangTimeShow = false 
             break;
          case '最近30天':
            timeObj.time = 30
            timeObj.start_time = getDateStr(-29)
            this.rangTimeShow = false
            break;
          case '今天':
             timeObj.time = 1
             timeObj.start_time = new Data()
             timeObj.end_time = getDateStr(1)
             this.rangTimeShow = false
             break;
          case '昨天':
             timeObj.time = -1
             timeObj.start_time = getDateStr(-1)
             this.rangTimeShow = false
             break;          
      }
      this.setDownloaderSearchTime(timeObj)
      
    //   console.log(this.downloaderSearch);
    },
    // 自定义时间
    rangTime() {
        this.selected = '自定义';
        this.rangTimeShow = true;
        if(this.dayshow) { 
        }else {
            this.downloaderSearch.time = ''
        }        
    },
    // 按小时设置自定义时间
    checkTime() {
        this.setDownloaderSearchTime({
            time: this.downloaderSearch.time,
            start_time: this.downloaderSearch.time,
            end_time: getNextDay(this.downloaderSearch.time)
        })
    },
     // 选择时间的类型
    chooseTimeType(type) {
        if(type === 'day') {
            this.dayshow = true;
            this.downloaderSearch.cycle = 'day'
        }else if(type === 'time') {
            this.dayshow = false;
            this.selected = '今天';
            this.rangTimeShow = false;
            this.downloaderSearch.cycle = 'hour'
            this.setDownloaderSearchTime({
                time: 1,
                start_time: new Date(),
                end_time: getDateStr(1)
            }) 
        }
    },
    setRang() {
        let obj = {
          time: this.downloaderSearch.time,
          start_time: this.downloaderSearch.time[0],
          end_time: this.downloaderSearch.time[1]
        }
        this.setDownloaderSearchTime(obj)   
    },
    getData() {
      console.log(this.downloaderSearch);
      console.log(this.requestData)
      axios.get(DownloaderSitedataUrl, { headers: getHeader(), params: this.requestData})
      .then(response => {
          if(response.status === 200 && response.data.success) {
              this.tableData = [];
              this.tableData = response.data.data
              this.setChartData()
          }else {
              this.$message.error('获取列表失败 !')
          }
          console.log(response)
      })
      .catch((e) => {
        this.$message.error('获取列表失败 !')
      })
    },
    formatterNumber(row, column, cellValue, index) {
        return parseInt(cellValue).toLocaleString()           
    },
    handleDownload() { //导出excel
        this.downloadLoading = true;
        let _this = this;
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          let thead = ['week', 'date', 'open', 'one', 'two', 'three', 'success', 'error', 'success_rate', 'error_rate' ]
          const tHeader = ['周数', '时间', '打开量', '第一步', '第二步', '第三步', '成功', '失败', '成功率', '失败率']
          const list = _this.tableData;
          const filterVal = thead;
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '下载器明细分析excel')
          this.downloadLoading = false
        })
    },
     formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map( j => {
                if(v[j] === undefined ) {
                    return v[j] = '';
                }else {
                    return v[j]
                }
                
            }
            
        ))
    },
    search() {
        this.getData()
    },
    setChartData() {
        // 设置图表组件的数据
        let _this = this;
        this.lineChartData['xAxisData'] = [];
        this.lineChartData['legendData'] = ['打开量', '第一步', '第二步', '第三步', '成功量', '成功率'];
        this.lineChartData['seriesData']  = [];
        let openArr = [], successArr = [], success_rate = [], firstArr = [], twotArr = [], threeArr = [];
        this.tableData.forEach(v => {
            _this.lineChartData['xAxisData'].push(v.date);
            openArr.push(parseInt(v.open));
            successArr.push(parseInt(v.success));
            firstArr.push(v.one)
            twotArr.push(v.two)
            threeArr.push(v.three)
            let num = v.success_rate.replace(/%/ig,"");
            success_rate.push(parseFloat(num));
        })
        this.lineChartData['seriesData'][0] = openArr;
        this.lineChartData['seriesData'][1] = firstArr;
        this.lineChartData['seriesData'][2] = twotArr;
        this.lineChartData['seriesData'][3] = threeArr;
        this.lineChartData['seriesData'][4] = successArr;
        this.lineChartData['seriesData'][5] = success_rate;
    }
  }  
}
</script>

<style>
.blok-header {
  margin-bottom:10px;
}
.blok-header li{
    float: left;
    }
.blok-header  a {
    color: #666;

}    
</style>
